package console;

import java.awt.Color;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;


/**
 *
 * @author Michael Hanns
 *
 */
public class ServerHostDialog extends javax.swing.JDialog {

    private static final long serialVersionUID = -2481448775384265812L;
    private ClientObserver console;
    private ClientGUI terminal;

    /** Creates new form NewGameDialog */
    public ServerHostDialog(java.awt.Frame parent, boolean modal, ClientObserver cons) {
        super(parent, modal);
        this.console = cons;
        this.terminal = (ClientGUI)parent;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        serverNameLabel = new javax.swing.JLabel();
        advNameLabel = new javax.swing.JLabel();
        browseButton = new javax.swing.JButton();
        beginButton = new javax.swing.JButton();
        nameField = new javax.swing.JFormattedTextField();
        browseField = new javax.swing.JFormattedTextField();
        cancelButton = new javax.swing.JButton();
        maxPlayersLabel = new javax.swing.JLabel();
        capacityField = new javax.swing.JFormattedTextField();
        portLabel = new javax.swing.JLabel();
        portField = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Host Module");
        setLocationByPlatform(true);
        setResizable(false);

        serverNameLabel.setText("Server name:");

        advNameLabel.setText("Adventure file path:");

        browseButton.setText("Browse");
        browseButton.setToolTipText("Browse file system for adventure file.");
        browseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseButtonActionPerformed(evt);
            }
        });

        beginButton.setText("Begin");
        beginButton.setToolTipText("Begin specified adventure with new character.");
        beginButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                beginButtonActionPerformed(evt);
            }
        });

        nameField.setBackground(new java.awt.Color(255, 0, 0));
        nameField.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                nameFieldCaretUpdate(evt);
            }
        });

        browseField.setBackground(new java.awt.Color(255, 0, 0));
        browseField.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                browseFieldCaretUpdate(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        maxPlayersLabel.setText("Capacity:");

        capacityField.setText("24");
        capacityField.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                capacityFieldCaretUpdate(evt);
            }
        });

        portLabel.setText("Port:");

        portField.setText("1024");
        portField.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                portFieldCaretUpdate(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(advNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
                                .addGap(4, 4, 4))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(serverNameLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(nameField, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(maxPlayersLabel)
                                .addGap(8, 8, 8)
                                .addComponent(capacityField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(browseField, javax.swing.GroupLayout.DEFAULT_SIZE, 277, Short.MAX_VALUE)))
                    .addComponent(cancelButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(portLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(portField, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE))
                    .addComponent(browseButton)
                    .addComponent(beginButton, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(serverNameLabel)
                    .addComponent(portField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(capacityField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(maxPlayersLabel)
                    .addComponent(portLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(advNameLabel)
                    .addComponent(browseField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browseButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(beginButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void beginButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_beginButtonActionPerformed
        if (browseField.getBackground() != Color.red && capacityField.getBackground() != Color.red
                && portField.getBackground() != Color.red && nameField.getText().length() > 0) {
            console.sendToShell("serverhost " + capacityField.getText() + " "
                    + portField.getText() + " '" + nameField.getText() + "' '" + browseField.getText() + "'");
            dispose();
        }
    }//GEN-LAST:event_beginButtonActionPerformed

    private void browseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseButtonActionPerformed
        String fileName = filehandling.Opening.openPrompt();

        browseField.setText(fileName);
    }//GEN-LAST:event_browseButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void browseFieldCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_browseFieldCaretUpdate
        File test = new File(browseField.getText());
        // If its a .jml, continue
        if (test.exists() && browseField.getText().endsWith(".xml")) {
            try {
                // Read the file, make sure it starts with <adventure> tag
                FileReader reader = new FileReader(test);
                BufferedReader bufferedReader = new BufferedReader(reader);
                if (bufferedReader.readLine().startsWith("<adventure")) {
                    String lastLine = "";
                    String tempLine = "";

                    // Read it to the end now..
                    while ((tempLine = bufferedReader.readLine()) != null) {
                        lastLine = tempLine;
                    }
                    // And if it ends with </adventure>
                    if (lastLine != null && lastLine.equalsIgnoreCase("</adventure>")) {
                        browseField.setBackground(Color.white);
                    } else {
                        browseField.setBackground(Color.red);
                    }
                } else {
                    browseField.setBackground(Color.red);
                }
                bufferedReader.close();
                reader.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            browseField.setBackground(Color.red);
        }
    }//GEN-LAST:event_browseFieldCaretUpdate

    private void nameFieldCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_nameFieldCaretUpdate
        if (nameField.getText().length() > 0) {
            nameField.setBackground(Color.white);
        } else {
            nameField.setBackground(Color.red);
        }
    }//GEN-LAST:event_nameFieldCaretUpdate

    private void capacityFieldCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_capacityFieldCaretUpdate
        if (isInteger(capacityField.getText())) {
            capacityField.setBackground(Color.white);
        } else {
            capacityField.setBackground(Color.red);
        }
    }//GEN-LAST:event_capacityFieldCaretUpdate

    private void portFieldCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_portFieldCaretUpdate
        if (isInteger(portField.getText()) && Integer.parseInt(portField.getText()) != 724
                && Integer.parseInt(portField.getText()) != 725) {
            portField.setBackground(Color.white);
        } else {
            portField.setBackground(Color.red);
        }
    }//GEN-LAST:event_portFieldCaretUpdate

    // Helper methods
    private boolean isInteger(String intStr) {
        try {
            Integer.parseInt(intStr);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel advNameLabel;
    private javax.swing.JButton beginButton;
    private javax.swing.JButton browseButton;
    private javax.swing.JFormattedTextField browseField;
    private javax.swing.JButton cancelButton;
    private javax.swing.JFormattedTextField capacityField;
    private javax.swing.JLabel maxPlayersLabel;
    private javax.swing.JFormattedTextField nameField;
    private javax.swing.JFormattedTextField portField;
    private javax.swing.JLabel portLabel;
    private javax.swing.JLabel serverNameLabel;
    // End of variables declaration//GEN-END:variables
}
